'use client'

import { useEffect, useState, ReactNode, Suspense, useRef } from 'react'
import { useRouter, useSearchParams } from 'next/navigation'
import { useAuth } from '@/contexts/AuthClientContext'
import { message } from '@/utils/toast'

interface AutoLoginProps {
  children: ReactNode
}

function AutoLoginInner({ children }: AutoLoginProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { login } = useAuth()
  const [isProcessing, setIsProcessing] = useState(false)
  const [hasProcessed, setHasProcessed] = useState(false)
  const [loginStatus, setLoginStatus] = useState<'checking' | 'processing' | 'success' | 'error' | 'none'>('checking')
  const processedRef = useRef(false) // 使用ref避免重复处理

  useEffect(() => {
    const handleAutoLogin = async () => {
      // 使用ref避免重复处理，确保只执行一次
      if (processedRef.current || isProcessing) return

      const token = searchParams?.get('token')
      const userInfo = searchParams?.get('user')
      const source = searchParams?.get('source') || 'unknown'
      const isFirstLogin = searchParams?.get('isFirstLogin') === 'true'

      // 如果URL中有token，说明是从外部跳转过来的
      if (token) {
        console.log(`开始处理${source}自动登录`)
        processedRef.current = true
        setIsProcessing(true)
        setHasProcessed(true)
        setLoginStatus('processing')
        
        try {
          // 使用AuthContext的login方法保存token
          login(token)
          
          let user = { name: '' }
          if (userInfo) {
            try {
              user = JSON.parse(decodeURIComponent(userInfo))
            } catch (error) {
              console.error('用户信息解析失败:', error)
              // 不显示错误，继续处理
            }
          }
          
          // 根据来源显示不同的欢迎消息
          let welcomeMessage = ''
          if (source === 'admin') {
            welcomeMessage = `管理员已为您生成登录链接，欢迎${user.name || ''}！`
          } else if (source === 'wechat') {
            welcomeMessage = isFirstLogin ? `欢迎加入，${user.name || ''}！` : `欢迎回来，${user.name || ''}！`
          } else {
            welcomeMessage = `欢迎${user.name || ''}！`
          }
          
          message.success(welcomeMessage)

          // 清理URL参数，避免刷新页面时重复处理
          const newUrl = new URL(window.location.href)
          newUrl.searchParams.delete('token')
          newUrl.searchParams.delete('user')
          newUrl.searchParams.delete('source')
          newUrl.searchParams.delete('isFirstLogin')

          // 使用 replaceState 清理URL，不会触发页面重新加载
          window.history.replaceState({}, '', newUrl.toString())

          console.log(`${source}自动登录处理完成`)
          setLoginStatus('success')

          // 短暂显示成功状态后，切换到正常渲染
          setTimeout(() => {
            setLoginStatus('none')
          }, 1500)

        } catch (error) {
          console.error(`${source}自动登录处理失败:`, error)
          message.error('登录信息处理失败，请重新登录')
          setLoginStatus('error')

          // 清理URL参数
          const newUrl = new URL(window.location.href)
          newUrl.searchParams.delete('token')
          newUrl.searchParams.delete('user')
          newUrl.searchParams.delete('source')
          newUrl.searchParams.delete('isFirstLogin')
          window.history.replaceState({}, '', newUrl.toString())

          // 3秒后跳转到登录页
          setTimeout(() => {
            router.push('/login')
          }, 3000)
        } finally {
          setIsProcessing(false)
        }
      } else {
        // 没有登录参数，正常渲染页面
        setLoginStatus('none')
      }
    }

    handleAutoLogin()
  }, [searchParams, login, router, isProcessing]) // 移除hasProcessed依赖，避免重复调用

  // 根据登录状态决定渲染内容
  if (loginStatus === 'checking') {
    // 初始检查状态，显示简单加载
    return (
      <div className="fixed inset-0 bg-white flex items-center justify-center z-50">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    )
  }

  if (loginStatus === 'processing') {
    // 正在处理自动登录
    return (
      <div className="fixed inset-0 bg-white flex items-center justify-center z-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <h2 className="text-xl font-semibold mb-2">正在登录...</h2>
          <p className="text-gray-600">正在验证您的身份</p>
        </div>
      </div>
    )
  }

  if (loginStatus === 'success') {
    // 登录成功
    return (
      <div className="fixed inset-0 bg-white flex items-center justify-center z-50">
        <div className="text-center">
          <div className="h-12 w-12 mx-auto mb-4 text-green-600">
            <svg className="w-full h-full" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
            </svg>
          </div>
          <h2 className="text-xl font-semibold mb-2 text-green-700">登录成功！</h2>
          <p className="text-gray-600">正在跳转到系统...</p>
        </div>
      </div>
    )
  }

  if (loginStatus === 'error') {
    // 登录失败
    return (
      <div className="fixed inset-0 bg-white flex items-center justify-center z-50">
        <div className="text-center">
          <div className="h-12 w-12 mx-auto mb-4 text-red-600">
            <svg className="w-full h-full" fill="currentColor" viewBox="0 0 20 20">
              <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
            </svg>
          </div>
          <h2 className="text-xl font-semibold mb-2 text-red-700">登录失败</h2>
          <p className="text-gray-600 mb-4">登录信息处理失败，请重新登录</p>
          <p className="text-sm text-gray-500">3秒后自动跳转到登录页...</p>
        </div>
      </div>
    )
  }

  // loginStatus === 'none'，正常渲染页面内容
  return <>{children}</>
}

export function AutoLogin({ children }: AutoLoginProps) {
  return (
    <Suspense fallback={<div>{children}</div>}>
      <AutoLoginInner>{children}</AutoLoginInner>
    </Suspense>
  )
}

// 为了保持向后兼容，保留原导出
export const WeChatAutoLogin = AutoLogin
